package com.qianbei.view;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.os.Vibrator;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.google.gson.Gson;
import com.qianbei.R;
import com.qianbei.bean.GetBoxInfo;
import com.qianbei.bean.GetBoxInfoType;
import com.qianbei.bean.GetCarbean;
import com.qianbei.bean.GetEmpty_Body;
import com.qianbei.bean.GetUpbox2;
import com.qianbei.bean.GetuploandBean;
import com.qianbei.common.base.BaseActivity;
import com.qianbei.common.base.MyApplication;
import com.qianbei.common.init.SetData;
import com.qianbei.common.net.control.ServerControl;
import com.qianbei.common.net.control.ServerResult;
import com.qianbei.common.net.okhttp.RequeastBean;
import com.qianbei.common.net.view.MsgAlert;
import com.qianbei.common.net.view.ProgressDialog;
import com.qianbei.common.util.DeviceUtil;
import com.qianbei.view.adapter.ScanAdapter;
import com.qianbei.view.db.BoxDb;
import com.qianbei.view.orm.DaoSession;
import com.qianbei.view.orm.RFID;
import com.qianbei.view.orm.RFIDDao;
import com.qianbei.view.orm.RequestPersistent;
import com.qianbei.view.util.JobBoxUtil;
import com.qianbei.view.util.MessageCallback;
import com.speedata.libuhf.IUHFService;
import com.speedata.libuhf.UHFManager;
import com.speedata.libuhf.bean.SpdInventoryData;
import com.speedata.libuhf.interfaces.OnSpdInventoryListener;

import org.greenrobot.greendao.query.QueryBuilder;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.atomic.AtomicBoolean;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.OnTouch;

/**
 * 卸车
 * Created by gaoml on 2018/1/18.
 */

public class UnloadActivity extends BaseActivity {


    @Bind(R.id.rfid_txt)
    TextView rfidTxt;

    @Bind(R.id.vehicle2_number_txt)
    TextView vehicle2Number;

    @Bind(R.id.unload_vehicle_title)
    TextView unloadTitle;

    @Bind(R.id.switch2)
    Switch switch2;

    @Bind(R.id.switch2_layout)
    RelativeLayout switch2Layout;

    @Bind(R.id.boxinfo)
    TextView boxinfo;

    @Bind(R.id.scan_stat_info)
    TextView scanStat;

    @Bind(R.id.finish_scan)
    TextView finish;

    private int init_progress = 0;
    private PowerManager pM = null;
    private PowerManager.WakeLock wK = null;
    private IUHFService iuhfService;


    private ListView EpcList;
    private TextView Status;
    private List<EpcDataBase> firm = new ArrayList<EpcDataBase>();
    private ScanAdapter adapter;


    int id = 1; // 1 扫描车 2 扫描 货物  3扫驳运车

    private String jobid;//通过车辆FRD获得的


    /**
     * 驳运车RFID
     */
    private String transportRFID;
    /**
     * 是否上电状态
     */
    private AtomicBoolean isOpenDev = new AtomicBoolean(false);

    /**
     * 成功上电
     */
    private AtomicBoolean isOpenSucces = new AtomicBoolean(false);

    /**
     *
     */
    private Set<String> alreadySave = new HashSet<String>();
    private RFIDDao rfidDao;

    private BoxDb boxDb;

    ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1);

    private AtomicBoolean canRead = new AtomicBoolean(false);
    private boolean scanedVehicle;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.gufei_unload_acitivty);

        ButterKnife.bind(this);

        EpcList = (ListView) findViewById(R.id.listView_search_epclist);
        Status = (TextView) findViewById(R.id.textView_search_status);
        findViewById(R.id.vehicle2_layout).setVisibility(View.GONE);
        findViewById(R.id.switch2_layout).setVisibility(View.GONE);
        findViewById(R.id.scan_stat).setVisibility(View.GONE);
        findViewById(R.id.boxnum_load).setVisibility(View.GONE);


        adapter = new ScanAdapter(
                this, firm, R.layout.gufei_item_scan);
        EpcList.setAdapter(adapter);

        adapter.setStatus(Status);
        adapter.setStat(scanStat);
        adapter.setShortTxt(true);
        adapter.setDelCallback(new MessageCallback() {
            @Override
            public void call() {
                updateStatus();
            }
        });

        findViewById(R.id.scan_stat).setVisibility(View.GONE);

        setTitle("到场卸车");
        mTitle.setrightTitle("扫描车辆");
//            iuhfService = UHFManager.getUHFService(UnloadActivity.this);
        iuhfService = MyApplication.iuhfService;


        newWakeLock();

        DaoSession daoSession = ((MyApplication) getApplication()).getDaoSession();
        rfidDao = daoSession.getRFIDDao();

        boxDb = new BoxDb(this);

    }

    private void newWakeLock() {
        init_progress++;
        pM = (PowerManager) getSystemService(POWER_SERVICE);
        if (pM != null) {
            wK = pM.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK
                    | PowerManager.ON_AFTER_RELEASE, "lock3992");
            if (wK != null) {
                wK.acquire();
                init_progress++;
            }
        }
        if (init_progress == 1) {
            Log.w("3992_6C", "wake lock init failed");
        }
    }


    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 111://扫卸货车


                    SpdInventoryData var1 = (SpdInventoryData) msg.obj;
                    Log.d("gaoaa", var1.epc);

                    if (canRead.getAndSet(false) && !TextUtils.isEmpty(var1.epc)) {
                        ring();
                        iuhfService.newInventoryStop();
                        rfidTxt.setText(var1.epc);
                        select(var1.epc);

                        mTitle.setrightTitle("完成扫描");

                    }
                    break;


                case 222://周转箱
                    SpdInventoryData var = (SpdInventoryData) msg.obj;
                    Log.d("gaoaa", var.epc);
                    int j;
                    for (j = 0; j < firm.size(); j++) {
                        if (var.epc.equals(firm.get(j).epc)) {
                            firm.get(j).valid++;
                            firm.get(j).setRssi(var.rssi);
                            break;
                        }
                    }
                    if (j == firm.size()) {
                        if (canRead.getAndSet(false)) {

                            final EpcDataBase epcDataBase = new EpcDataBase(var.epc, 1,
                                    var.rssi, var.tid);

                            ring();
                            mTitle.setrightTitle("完成扫描");
                            iuhfService.newInventoryStop();

                            JobBoxUtil.getBoxType(boxDb, epcDataBase, new MessageCallback() {
                                @Override
                                public void call() {
                                    if (!TextUtils.isEmpty(jobid)) {
                                        QueryBuilder<RFID> qb = rfidDao.queryBuilder();
                                        // 指定派车单 指定客户 指定箱子类型 条件查询
                                        qb.where(qb.and(RFIDDao.Properties.JobId.eq(SetData.getJobid()), RFIDDao.Properties.Rfid.eq(epcDataBase.epc), RFIDDao.Properties.WhichStep.eq("BoxUnload")));

                                        List<RFID> queryRfid = qb.list();
                                        if (queryRfid.size() == 0) {
                                            RFID rfid = new RFID();

                                            rfid.setJobId(jobid);
                                            rfid.setWhichStep("BoxUnload");
                                            rfid.setRfid(epcDataBase.epc);
                                            rfid.setBoxNum(epcDataBase.boxId);
                                            rfid.setBoxType(epcDataBase.boxType);

                                            if (!TextUtils.isEmpty(epcDataBase.typeValue)) {
                                                rfid.setBoxTypeIntVal(Integer.valueOf(epcDataBase.typeValue));
                                            }

                                            rfidDao.save(rfid);

                                        } else {
                                            RFID rfid = queryRfid.get(0);
                                            rfid.setBoxNum(epcDataBase.boxId);
                                            rfid.setBoxType(epcDataBase.boxType);


                                            if (!TextUtils.isEmpty(epcDataBase.typeValue)) {
                                                rfid.setBoxTypeIntVal(Integer.valueOf(epcDataBase.typeValue));
                                            }

                                            rfidDao.update(rfid);
                                        }

                                        firm.clear();

                                        firm.add(0, epcDataBase);
                                        adapter.notifyDataSetChanged();
                                        updateStatus();
                                    }

                                }
                            });


                            mTitle.setrightTitle("完成扫描");
                            iuhfService.newInventoryStop();
                        }
                    }

                    adapter.notifyDataSetChanged();

                    //Status.setText("扫描数量: " + firm.size());
                    break;
                case 333:
                    //驳运车

                    if (canRead.getAndSet(false)) {
                        ring();
                        SpdInventoryData var2 = (SpdInventoryData) msg.obj;
                        Log.d("gaoaa", var2.epc);
                        if (!TextUtils.isEmpty(var2.epc)) {
                            transportRFID = var2.epc;
                            vehicle2Number.setText(var2.epc);
                            iuhfService.newInventoryStop();
                            mTitle.setrightTitle("完成扫描");
                            selectVehicleNumber(var2.epc);

                            id = 2; //转换为扫周转箱
                        }
                    }
                    break;

                case 2:
                    mTitle.setrightTitle("完成扫描");
                    iuhfService.newInventoryStop();
                    break;
            }
        }
    };


    private void ring() {


        Uri notification = Uri.parse("android.resource://" + getApplicationContext().getPackageName() + "/" + R.raw.beep_once);
        if (notification == null) return;
        Ringtone r = RingtoneManager.getRingtone(this, notification);
        r.play();

        Vibrator vibrator = (Vibrator) this.getSystemService(Context.VIBRATOR_SERVICE);
        vibrator.vibrate(500);
    }

    private void vibrate() {
        Vibrator vibrator = (Vibrator) this.getSystemService(Context.VIBRATOR_SERVICE);
        vibrator.vibrate(100);
    }

    /**
     * 上电开串口
     *
     * @return
     */
    private boolean openDev() {
        if (iuhfService.OpenDev() != 0) {
            new android.app.AlertDialog.Builder(this).setTitle(R.string.DIA_ALERT).setMessage(R.string.DEV_OPEN_ERR).setPositiveButton(R.string.DIA_CHECK, new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // TODO Auto-generated method stub
                    finish();
                }
            }).show();
            return true;
        }
        return false;
    }

    @Override
    protected void onResume() {
        super.onResume();

        mTitle.setrightTitle("完成扫描");

        Log.d("Resume", id + "");
        isOpenDev.set(false);

        iuhfService.setOnInventoryListener(new OnSpdInventoryListener() {
            @Override
            public void getInventoryData(SpdInventoryData var1) {
                if (id == 1) {
                    handler.sendMessage(handler.obtainMessage(111, var1));
                } else if (id == 2) {
                    handler.sendMessage(handler.obtainMessage(222, var1));
                } else if (id == 3) {
                    handler.sendMessage(handler.obtainMessage(333, var1));
                }
            }
        });

        if (!TextUtils.isEmpty(SetData.getJobid())) {
            Log.d("s", SetData.getJobid());

            if (firm != null && firm.size() > 0) {
                for (final EpcDataBase epcDataBase : firm) {
                    JobBoxUtil.getBoxType(boxDb, epcDataBase, new MessageCallback() {
                        @Override
                        public void call() {
                            QueryBuilder<RFID> qb = rfidDao.queryBuilder();

                            if (!TextUtils.isEmpty(epcDataBase.epc)) {
                                qb.where(qb.and(RFIDDao.Properties.JobId.eq(SetData.getJobid()), RFIDDao.Properties.WhichStep.eq("BoxUnload"),
                                        RFIDDao.Properties.Rfid.eq(epcDataBase.epc)));
                            } else {
                                qb.where(qb.and(RFIDDao.Properties.JobId.eq(SetData.getJobid()), RFIDDao.Properties.WhichStep.eq("BoxUnload"),
                                        RFIDDao.Properties.BoxNum.eq(epcDataBase.boxId)));
                            }

                            List<RFID> queryRfid = qb.list();

                            if (queryRfid.size() == 1) {
                                RFID rfid = queryRfid.get(0);
                                rfid.setRfid(epcDataBase.epc);
                                rfid.setBoxNum(epcDataBase.boxId);
                                rfid.setBoxType(epcDataBase.boxType);
                                if (!TextUtils.isEmpty(epcDataBase.typeValue)) {
                                    rfid.setBoxTypeIntVal(Integer.valueOf(epcDataBase.typeValue));
                                }
                                rfidDao.update(rfid);
                            }

                        }
                    });
                }

                Collections.sort(firm);
            }

        }

        adapter.notifyDataSetChanged();
        if (scanedVehicle) {
            updateStatus();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        try {
            if (iuhfService != null && isOpenDev.get() == true) {
                iuhfService.newInventoryStop();
                iuhfService.CloseDev();
                //断电后选卡操作会失效，需要重新选卡（掩码）
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Override
    public void fClick(int id) {
        super.fClick(id);
        switch (id) {
            case R.id.tv_right:
                confirmFinish(findViewById(R.id.finish_scan));
                break;
            default:
                break;
        }
    }


    @SuppressLint("StaticFieldLeak")
    @OnTouch(R.id.finish_scan)
    public boolean onTouch(View v, MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                Log.d("touchEven", "down");
                Log.d("fClick:", isOpenDev.get() + "");
                vibrate();
                finish.setBackgroundColor(getResources().getColor(R.color.color_4d9dce));
                mTitle.setrightTitle("扫描中...");
                //重复点扫描按钮时 只做一次上电操作
                if (isOpenDev.get() == false) {
                    isOpenDev.set(true);
                    new AsyncTask<Void, Void, Void>() {
                        @Override
                        protected Void doInBackground(Void... voids) {
                            try {
                                if (openDev()) {
                                    isOpenDev.set(false);
                                    return null;
                                } else {
                                    isOpenSucces.set(true);
                                }
                                iuhfService.set_antenna_power(MyApplication.setValue);
                            } catch (Exception e) {
                                e.printStackTrace();
                                isOpenDev.set(false);
                                return null;
                            }
                            iuhfService.newInventoryStart();
                            canRead.set(true);
                            return null;
                        }
                    }.execute();

                } else if (isOpenSucces.get() == true) {
                    iuhfService.newInventoryStart();
                    canRead.set(true);

                }
                break;
            case MotionEvent.ACTION_UP:
                Log.d("touchEven", "up");
                finish.setBackgroundColor(getResources().getColor(R.color.color_519DCC));
                mTitle.setrightTitle("完成扫描");
                if (isOpenSucces.get() == true) {
                    iuhfService.newInventoryStop();
                } else {
                    delayStop();
                }
                break;
            default:
                break;
        }
        return true;
    }


    /**
     * 更新扫描大小箱计数
     */
    private void updateStatus() {
        if (!TextUtils.isEmpty(SetData.getJobid())) {
            QueryBuilder<RFID> qb = rfidDao.queryBuilder();
            qb.where(qb.and(RFIDDao.Properties.JobId.eq(SetData.getJobid()), RFIDDao.Properties.WhichStep.eq("BoxUnload")));
            List<RFID> queryRfid = qb.list();

            JobBoxUtil util = new JobBoxUtil();
            String count = util.countBox(queryRfid, true);
            Status.setText(count);
            scanStat.setText(count);

        }
    }

    private void delayStop() {

        handler.sendEmptyMessageDelayed(2, 5000);

    }

    /**
     * 提示用户 绑定
     */
    public void show() {
        AlertDialog dialog = new AlertDialog.Builder(this)
//                .setTitle("是否绑定此车")//设置对话框的标题
                .setMessage("是否绑定此车？")//设置对话框的内容
                //设置对话框的按钮
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
//                        checkVehicle();
                        dialog.dismiss();
                    }
                }).create();
        dialog.show();
    }

    @OnClick(R.id.boxnum_add)
    public void boxNumClick(View view) {
        boxnumAdd();
    }

    /**
     * 按箱号添加
     */
    public void boxnumAdd() {
        String boxNum = ((EditText) findViewById(R.id.boxnumber)).getText().toString();
        Log.d("BoxNumberAdd", boxNum);
        if (TextUtils.isEmpty(boxNum)) {
            new MsgAlert().show("请输入箱子编号");
            return;
        }

        boxNum = boxNum.trim();
        final EpcDataBase epc = new EpcDataBase("", 1,
                "", "");
        epc.setBoxType("");
        epc.setBoxId(boxNum);


        final String finalBoxNum = boxNum;
        JobBoxUtil.getBoxType(boxDb, epc, new MessageCallback() {
            @Override
            public void call() {
                QueryBuilder<RFID> qb = rfidDao.queryBuilder();
                // 指定派车单 指定客户 指定箱子类型 条件查询
                qb.where(qb.and(RFIDDao.Properties.JobId.eq(SetData.getJobid()), RFIDDao.Properties.BoxNum.eq(finalBoxNum), RFIDDao.Properties.WhichStep.eq("BoxUnload")
                ));

                List<RFID> queryRfid = qb.list();
                if (queryRfid.size() == 0) {

                    RFID rfid = new RFID();
                    rfid.setJobId(SetData.getJobid());
                    rfid.setWhichStep("BoxUnload");
                    if (!TextUtils.isEmpty(epc.boxId)) {
                        rfid.setBoxNum(epc.boxId);
                    } else {
                        rfid.setBoxNum(finalBoxNum);
                        epc.setBoxId(finalBoxNum);
                    }
                    rfid.setBoxType(epc.boxType);
                    rfid.setRfid(epc.epc);
                    if (!TextUtils.isEmpty(epc.typeValue)) {
                        rfid.setBoxTypeIntVal(Integer.valueOf(epc.typeValue));
                    }

                    rfidDao.save(rfid);

                } else {
                    RFID rfid = queryRfid.get(0);
                    if (!TextUtils.isEmpty(epc.boxId)) {
                        rfid.setBoxNum(epc.boxId);
                    } else {
                        rfid.setBoxNum(finalBoxNum);
                        epc.setBoxId(finalBoxNum);
                    }

                    rfid.setRfid(epc.epc);
                    rfid.setBoxType(epc.boxType);
                    if (!TextUtils.isEmpty(epc.typeValue)) {
                        rfid.setBoxTypeIntVal(Integer.valueOf(epc.typeValue));
                    }

                    rfidDao.update(rfid);
                }

                firm.clear();

                firm.add(0, epc);
                adapter.notifyDataSetChanged();
                updateStatus();

                ((EditText) findViewById(R.id.boxnumber)).setText("");

            }
        });


        new MsgAlert().show("添加成功");
    }

    private String msg = "确认完成扫描？";

    public void confirmFinish(final View view) {
        AlertDialog dialog = new AlertDialog.Builder(this)
                .setMessage(msg)
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finishScan(view);
                        dialog.dismiss();
                    }
                }).create();
        dialog.show();
    }


    public void finishScan(View view) {
        String tag = (String) view.getTag();
        if (tag != null && tag.equals("finish")) {
            findViewById(R.id.scan_stat).setVisibility(View.VISIBLE);

            if (!TextUtils.isEmpty(SetData.getJobid())) {
                QueryBuilder<RFID> qb = rfidDao.queryBuilder();
                qb.where(qb.and(RFIDDao.Properties.JobId.eq(SetData.getJobid()), RFIDDao.Properties.WhichStep.eq("BoxUnload")));


                List<RFID> queryRfid = qb.list();

                if (queryRfid.size() > 0) {
                    for (RFID rfid : queryRfid) {
                        EpcDataBase epcDataBase = new EpcDataBase(rfid.getRfid(), 1,
                                "", "");
                        epcDataBase.setBoxId(rfid.getBoxNum());
                        epcDataBase.setEpc(rfid.getRfid());
                        epcDataBase.setBoxType(rfid.getBoxType());
                        epcDataBase.setTypeValue(rfid.getBoxTypeIntVal() + "");

                        if (!firm.contains(epcDataBase)) {
                            firm.add(epcDataBase);
                        }
                    }

                }
            }

            Collections.sort(firm);

            adapter.notifyDataSetChanged();
            adapter.updateStatusText(false);
            adapter.updateStat();


            finish.setText("保存");
            msg = "确认保存？";
            view.setTag("save");
            finish.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    confirmFinish(v);
                }
            });

            finish.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    return false;
                }
            });

        } else if (tag.equals("save")) {
            if (TextUtils.isEmpty(jobid)) {
                new MsgAlert().show("请重新扫描车辆信息");
            } else {
                if (firm == null || firm.size() == 0) {
                    new MsgAlert().show("请完成扫描");
                    return;
                }
                if (switch2.isChecked() && (transportRFID == null || transportRFID.trim().length() == 0)) {
                    new MsgAlert().show("请扫描驳运车");
                    return;
                }

                select2(jobid);
            }
        }


    }

    /**
     * 是否卸到驳运车
     *
     * @param view
     */
    @OnClick(R.id.switch2)
    public void switchTransport(View view) {
        boolean checked = switch2.isChecked();
        LinearLayout layout = (LinearLayout) findViewById(R.id.vehicle2_layout);
        if (checked) {
            layout.setVisibility(View.VISIBLE);
        } else {
            layout.setVisibility(View.GONE);
        }
    }

    //@OnClick(R.id.unload_vehicle_title)
    public void hideVehilce() {
        RelativeLayout layout = (RelativeLayout) findViewById(R.id.unload_vehicle_info);
        ViewGroup.LayoutParams params = layout.getLayoutParams();

        RelativeLayout layoutSwitch = (RelativeLayout) findViewById(R.id.switch2_layout);
        ViewGroup.LayoutParams paramsSwitch = layoutSwitch.getLayoutParams();

        if (layout.getTag(R.id.unload_vehicle) == null || layout.getTag(R.id.unload_vehicle).equals("show")) {
            params.height = 2;
            paramsSwitch.height = 0;
            layout.setTag(R.id.unload_vehicle, "hide");
        } else {
            params.height = 120;
            paramsSwitch.height = 260;
            layout.setTag(R.id.unload_vehicle, "show");
        }

        layout.setLayoutParams(params);
        layoutSwitch.setLayoutParams(paramsSwitch);
    }

    //@OnClick(R.id.vehicle2_title)
    public void hideVehilce2() {
        RelativeLayout layout = (RelativeLayout) findViewById(R.id.vehicle2_info);
        ViewGroup.LayoutParams params = layout.getLayoutParams();
        if (layout.getTag(R.id.vehicle2_info) == null || layout.getTag(R.id.vehicle2_info).equals("show")) {
            params.height = 2;
            layout.setTag(R.id.vehicle2_info, "hide");
        } else {
            params.height = 120;
            layout.setTag(R.id.vehicle2_info, "show");
        }

        layout.setLayoutParams(params);
    }

    //@OnClick(R.id.top_temp)
    public void hideAllVehilce() {
        RelativeLayout layout = (RelativeLayout) findViewById(R.id.top_temp);

        if (layout.getTag(R.id.top_temp) == null || layout.getTag(R.id.top_temp).equals("show")) {
            layout.setTag(R.id.top_temp, "hide");

            findViewById(R.id.unload_vehicle_title).setVisibility(View.GONE);
            findViewById(R.id.unload_vehicle_info).setVisibility(View.GONE);
            findViewById(R.id.switch2_layout).setVisibility(View.GONE);
            findViewById(R.id.vehicle2_layout).setVisibility(View.GONE);
        } else {
            layout.setTag(R.id.top_temp, "show");

            findViewById(R.id.unload_vehicle_title).setVisibility(View.VISIBLE);
            findViewById(R.id.unload_vehicle_info).setVisibility(View.VISIBLE);
            findViewById(R.id.switch2_layout).setVisibility(View.VISIBLE);
            findViewById(R.id.vehicle2_layout).setVisibility(View.VISIBLE);

        }


    }


    /**
     * 获取车辆信息
     *
     * @return
     */

    private void select(String fid) {

        ServerControl sc = new ServerControl(
                new RequeastBean("uninstallVehicle", "com.cygps.dubbo.WasteTransport.IPdaBoxManagement",
                        new GetuploandBean(fid)));
        sc.serverListener = new ServerControl.ServerListener() {

            @Override
            public void serverFinish(ServerResult sr) {
                if (sr.isContinue) {
                    jobid = sr.bodyData.optString("jobId");
                    SetData.setJobid(jobid);
                    String vehicleNumber = sr.bodyData.optString("vehicleNumber");
                    rfidTxt.setText(vehicleNumber);
                    scanedVehicle = true;
                    getScanBox();
                    getJobInfo(sr.bodyData);
                    id = 2; //转换为扫周转箱


                    switch2Layout.setVisibility(View.VISIBLE);
                    findViewById(R.id.boxnum_load).setVisibility(View.VISIBLE);
                    ((TextView) findViewById(R.id.finish_scan)).setText("按住扫描周转箱");
                } else {
                    id = 1;//扫车
                }

            }
        };
        new ProgressDialog(mContext).OKpost(sc);
    }

    private void getJobInfo(JSONObject bodyData) {
        JSONObject boxInfoObj = bodyData.optJSONObject("boxinfo");
        GetBoxInfo boxInfo = JSON.parseObject(boxInfoObj.toString(), new TypeReference<GetBoxInfo>() {
        });
        if (boxInfo == null) {
            return;
        }

        StringBuffer buf = new StringBuffer();
        buf.append("总箱数：" + boxInfo.getCount() + "\n");
        buf.append("空箱  " + "小箱:" + boxInfo.empty.small + " " + "    大箱:" + boxInfo.empty.big + "\n");
        buf.append("重箱  " + "小箱:" + boxInfo.full.small + " " + "    大箱:" + boxInfo.full.big + "    箱号装车:" + boxInfo.getBoxNumLoad());

        boxinfo.setText(buf.toString());


    }


    /**
     * 查询缓存的RFID
     */
    private void getScanBox() {

        if (!TextUtils.isEmpty(SetData.getJobid())) {
            QueryBuilder<RFID> qb = rfidDao.queryBuilder();
            qb.where(qb.and(RFIDDao.Properties.JobId.eq(SetData.getJobid()), RFIDDao.Properties.WhichStep.eq("BoxUnload")));


            List<RFID> queryRfid = qb.list();

            if (queryRfid.size() > 0) {
                for (RFID rfid : queryRfid) {
                    final EpcDataBase epcDataBase = new EpcDataBase(rfid.getRfid(), 1,
                            "", "");
                    epcDataBase.setBoxId(rfid.getBoxNum());
                    epcDataBase.setEpc(rfid.getRfid());
                    epcDataBase.setBoxType(rfid.getBoxType());
                    epcDataBase.setTypeValue(rfid.getBoxTypeIntVal() + "");

                    JobBoxUtil.getBoxType(boxDb, epcDataBase, new MessageCallback() {
                        @Override
                        public void call() {
                            QueryBuilder<RFID> qb = rfidDao.queryBuilder();

                            if (!TextUtils.isEmpty(epcDataBase.epc)) {
                                qb.where(qb.and(RFIDDao.Properties.JobId.eq(SetData.getJobid()), RFIDDao.Properties.WhichStep.eq("BoxUnload"),
                                        RFIDDao.Properties.Rfid.eq(epcDataBase.epc)));
                            } else {
                                qb.where(qb.and(RFIDDao.Properties.JobId.eq(SetData.getJobid()), RFIDDao.Properties.WhichStep.eq("BoxUnload"),
                                        RFIDDao.Properties.BoxNum.eq(epcDataBase.boxId)));
                            }

                            List<RFID> queryRfid = qb.list();

                            if (queryRfid.size() == 1) {
                                RFID rfid = queryRfid.get(0);
                                rfid.setRfid(epcDataBase.epc);
                                rfid.setBoxNum(epcDataBase.boxId);
                                rfid.setBoxType(epcDataBase.boxType);
                                if (!TextUtils.isEmpty(epcDataBase.typeValue)) {
                                    rfid.setBoxTypeIntVal(Integer.valueOf(epcDataBase.typeValue));
                                }
                                rfidDao.update(rfid);
                            }
                        }
                    });

                    if (!firm.contains(epcDataBase)) {
                        firm.add(epcDataBase);
                    }
                }

            }

            Collections.sort(firm);
        }

        adapter.notifyDataSetChanged();
        updateStatus();
    }

    /**
     * 查询驳运车车牌
     *
     * @param rfid
     */
    private void selectVehicleNumber(String rfid) {
        ServerControl sc = new ServerControl(
                new RequeastBean("getVehice", "com.cygps.dubbo.WasteTransport.IPDAGetVehicle",
                        new GetuploandBean(rfid)));
        sc.serverListener = new ServerControl.ServerListener() {

            @Override
            public void serverFinish(ServerResult sr) {
                if (sr.isContinue) {
                    String vehicleNum = sr.bodyData.optJSONObject("object").optString("vehicleNumber");
                    vehicle2Number.setText(vehicleNum);

                }

            }
        };
        new ProgressDialog(mContext).OKpost(sc);
    }

    /**
     * 卸车扫完RFID后保存
     *
     * @param
     */
    private void select2(String jobids) {
        ArrayList<String> where = new ArrayList<>();
        ArrayList<String> boxNum = new ArrayList<>();

        QueryBuilder<RFID> qb = rfidDao.queryBuilder();
        qb.where(qb.and(RFIDDao.Properties.JobId.eq(SetData.getJobid()), RFIDDao.Properties.WhichStep.eq("BoxUnload")));
        List<RFID> queryRfid = qb.list();

        if (queryRfid.size() > 0) {
            for (RFID rfid : queryRfid) {
                if (!TextUtils.isEmpty(rfid.getRfid())) {
                    where.add(rfid.getRfid());
                }else if(!TextUtils.isEmpty(rfid.getBoxNum())){
                    boxNum.add(rfid.getBoxNum());
                }
            }
        }


        boolean isToTransportVehicle = switch2.isChecked();
        RequeastBean bean = new RequeastBean("uninstallBox", "com.cygps.dubbo.WasteTransport.IPdaBoxManagement",
                new GetUpbox2(jobids, where, boxNum, transportRFID, isToTransportVehicle));
        if (!DeviceUtil.isNetworkAvailable()) {//没用网络 缓存数据到内存
//            MyApplication.netList.add(bean);bug001
            DaoSession daoSession = ((MyApplication) getApplication()).getDaoSession();
            RequestPersistent requestPersistent = new RequestPersistent();
            requestPersistent.setServiceName(bean.serviceName);
            requestPersistent.setServiceMethod(bean.serviceMethod);
            requestPersistent.setServiceBody(new Gson().toJson(bean.serviceBody));
            requestPersistent.setMethodClass(GetUpbox2.class.getName());
            daoSession.getRequestPersistentDao().insertOrReplace(requestPersistent);
            //new MsgAlert().show("现在没用网络，数据已保存 有网络的时候会自动提交");
            finish();
        } else {
            ServerControl sc = new ServerControl(bean);
            sc.serverListener = new ServerControl.ServerListener() {

                @Override
                public void serverFinish(ServerResult sr) {
                    if (sr.isContinue) {
                        int code = sr.bodyData.optInt("code");
                        new MsgAlert().show("保存成功");
                        finish();
                    }

                }
            };
            new ProgressDialog(mContext).OKpost(sc);
        }
    }


    @OnTouch({R.id.vehicle2_scan})
    public boolean onViewTouch(View v, MotionEvent event) {

        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                id = 3;
                vibrate();

                if (isOpenSucces.get() == true) {
                    mTitle.setrightTitle("扫描中...");
                    iuhfService.newInventoryStart();
                    canRead.set(true);
                }
                break;
            case MotionEvent.ACTION_UP:
                Log.d("touchEven", "up");
                mTitle.setrightTitle("完成扫描");

                if (isOpenSucces.get() == true) {
                    iuhfService.newInventoryStop();
                } else {
                    delayStop();
                }
                break;
            default:
                break;
        }

        return true;
    }
}
